<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - 设备报修系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: white;
            padding: 30px;
            border-radius: 16px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            color: #333;
            font-size: 28px;
        }

        .header p {
            color: #666;
            font-size: 14px;
        }

        .logout-btn {
            padding: 10px 24px;
            background: #ff4d4f;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
        }

        .logout-btn:hover {
            opacity: 0.9;
        }

        .login-panel {
            background: white;
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 400px;
            margin: 0 auto;
        }

        .login-panel h2 {
            margin-bottom: 20px;
            color: #333;
        }

        .login-panel input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            margin-bottom: 20px;
        }

        .login-panel button {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
        }

        .login-panel button:hover {
            opacity: 0.9;
        }

        .main-panel {
            display: none;
        }

        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .tab {
            padding: 12px 24px;
            background: white;
            border: none;
            border-radius: 8px 8px 0 0;
            cursor: pointer;
            font-size: 16px;
            color: #666;
            transition: all 0.3s;
        }

        .tab.active {
            background: white;
            color: #667eea;
            font-weight: bold;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
        }

        .tab-content {
            display: none;
            background: white;
            padding: 30px;
            border-radius: 0 16px 16px 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .tab-content.active {
            display: block;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f0f0f0;
        }

        .toolbar h2 {
            color: #333;
            font-size: 20px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: opacity 0.3s;
        }

        .btn:hover {
            opacity: 0.8;
        }

        .btn-primary {
            background: #1677ff;
            color: white;
        }

        .btn-success {
            background: #52c41a;
            color: white;
        }

        .btn-danger {
            background: #ff4d4f;
            color: white;
        }

        .btn-warning {
            background: #faad14;
            color: white;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th {
            background: #f5f5f5;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #333;
        }

        td {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        tr:hover {
            background: #f9f9f9;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
        }

        .badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-admin {
            background: #e6f7ff;
            color: #1677ff;
        }

        .badge-user {
            background: #f6ffed;
            color: #52c41a;
        }

        .badge-pending {
            background: #fff7e6;
            color: #faad14;
        }

        .badge-processing {
            background: #e6f7ff;
            color: #1677ff;
        }

        .badge-completed {
            background: #f6ffed;
            color: #52c41a;
        }

        .badge-rejected {
            background: #fff1f0;
            color: #ff4d4f;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-icon {
            font-size: 64px;
            margin-bottom: 20px;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.show {
            display: flex;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 16px;
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #1677ff;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
        }

        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 8px;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header" id="header" style="display:none;">
            <div>
                <h1>🛠️ 管理后台</h1>
                <p>设备报修系统 - 管理员控制面板</p>
            </div>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>

        <!-- 登录面板 -->
        <div class="login-panel" id="loginPanel">
            <h2>🔐 管理员登录</h2>
            <input type="password" id="adminKey" placeholder="请输入管理密钥" onkeypress="if(event.key==='Enter')login()" />
            <button onclick="login()">登录</button>
        </div>

        <!-- 主面板 -->
        <div class="main-panel" id="mainPanel">
            <!-- 标签页 -->
            <div class="tabs">
                <button class="tab active" onclick="switchTab('users')">👥 用户管理</button>
                <button class="tab" onclick="switchTab('labs')">🏫 机房管理</button>
                <button class="tab" onclick="switchTab('orders')">📋 工单管理</button>
                <button class="tab" onclick="switchTab('assets')">📦 资产管理</button>
                <button class="tab" onclick="switchTab('loans')">🔖 借用管理</button>
                <button class="tab" onclick="switchTab('inventory')">📊 盘点报废</button>
                <button class="tab" onclick="switchTab('spareparts')">🔧 备件管理</button>
                <button class="tab" onclick="switchTab('config')">⚙️ 系统配置</button>
            </div>

            <!-- 系统配置标签页 -->
            <div id="configTab" class="tab-content">
                <div class="tab-header">
                    <h2>系统配置</h2>
                </div>

                <div class="config-section">
                    <h3>📧 微信订阅消息模板配置</h3>
                    <p style="color:#666;margin-bottom:20px;">在微信公众平台配置订阅消息模板后，将模板ID填写到下方对应位置。</p>

                    <div class="form-group">
                        <label>微信小程序 AppID：</label>
                        <input type="text" id="wechat_app_id" placeholder="请输入AppID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;" />
                    </div>

                    <div class="form-group">
                        <label>微信小程序 AppSecret：</label>
                        <input type="password" id="wechat_app_secret" placeholder="请输入AppSecret"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;" />
                    </div>

                    <hr style="margin: 20px 0; border: 0; border-top: 1px solid #eee;" />

                    <!-- 借用相关模板 -->
                    <div style="background: #f8f9fa; padding: 12px; border-radius: 6px; margin-bottom: 16px;">
                        <h4 style="margin: 0; color: #495057; font-size: 16px;">📦 借用相关通知</h4>
                        <p style="margin: 8px 0 0 0; color: #6c757d; font-size: 13px;">用户在小程序中借用资产时会收到以下通知</p>
                    </div>

                    <div class="form-group">
                        <label>① 借用申请成功通知：<span style="color:#999;font-size:13px;">（用户提交借用申请后）</span></label>
                        <input type="text" id="template_loan_apply" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;" />
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_loan_apply')">编辑内容</button>
                    </div>

                    <div class="form-group">
                        <label>② 审批结果通知：<span style="color:#999;font-size:13px;">（管理员审批后）</span></label>
                        <input type="text" id="template_loan_approve" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;">
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_loan_approve')">编辑内容</button>
                    </div>

                    <div class="form-group">
                        <label>③ 归还提醒通知：<span style="color:#999;font-size:13px;">（临近归还日期时）</span></label>
                        <input type="text" id="template_loan_reminder" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;">
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_loan_reminder')">编辑内容</button>
                    </div>

                    <hr style="margin: 24px 0; border: 0; border-top: 2px solid #dee2e6;" />

                    <!-- 报修相关模板（用户）-->
                    <div style="background: #e8f4fd; padding: 12px; border-radius: 6px; margin-bottom: 16px;">
                        <h4 style="margin: 0; color: #0056b3; font-size: 16px;">🔧 报修相关通知（用户接收）</h4>
                        <p style="margin: 8px 0 0 0; color: #6c757d; font-size: 13px;">普通用户提交报修后会收到以下通知</p>
                    </div>

                    <div class="form-group">
                        <label>① 报修成功通知：<span style="color:#999;font-size:13px;">（用户提交报修后）</span></label>
                        <input type="text" id="template_repair_submit" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;">
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_repair_submit')">编辑内容</button>
                    </div>

                    <div class="form-group">
                        <label>② 维修接单通知：<span style="color:#999;font-size:13px;">（技术员接单后）</span></label>
                        <input type="text" id="template_repair_accept" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;">
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_repair_accept')">编辑内容</button>
                    </div>

                    <div class="form-group">
                        <label>③ 维修完成通知：<span style="color:#999;font-size:13px;">（技术员完成维修后）</span></label>
                        <input type="text" id="template_repair_complete" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;">
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_repair_complete')">编辑内容</button>
                    </div>

                    <hr style="margin: 24px 0; border: 0; border-top: 2px solid #dee2e6;" />

                    <!-- 报修相关模板（管理员）-->
                    <div style="background: #fff3cd; padding: 12px; border-radius: 6px; margin-bottom: 16px;">
                        <h4 style="margin: 0; color: #856404; font-size: 16px;">👨‍💼 报修相关通知（管理员接收）</h4>
                        <p style="margin: 8px 0 0 0; color: #6c757d; font-size: 13px;">管理员会收到新报修工单的推送</p>
                    </div>

                    <div class="form-group">
                        <label>新报修通知（管理员）：<span style="color:#999;font-size:13px;">（有用户提交报修时）</span></label>
                        <input type="text" id="template_admin_repair_notify" placeholder="请输入模板ID"
                            style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;">
                        <button class="btn btn-secondary" style="margin-top:8px;"
                            onclick="editTemplateContent('wechat_template_admin_repair_notify')">编辑内容</button>
                    </div>

                    <button class="btn btn-primary" onclick="saveConfig()" style="margin-top:20px;padding:12px 40px;">💾
                        保存配置</button>
                </div>

                <!-- 模板内容编辑弹窗 -->
                <div class="modal" id="templateContentModal">
                    <div class="modal-content" style="max-width:600px;">
                        <div class="modal-header" id="templateContentModalTitle">编辑模板内容</div>
                        <div class="form-group">
                            <label>模板参数（JSON）</label>
                            <textarea id="templateContentTextarea" rows="10"
                                style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;resize:vertical;"></textarea>
                        </div>
                        <div class="modal-footer">
                            <button class="btn" onclick="closeTemplateContentModal()">取消</button>
                            <button class="btn btn-primary" onclick="saveTemplateContent()">保存</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 用户管理标签页 -->
            <div class="tab-content active" id="usersTab">
                <div class="toolbar">
                    <h2>用户列表</h2>
                    <div style="display:flex;gap:15px;align-items:center;">
                        <button class="btn btn-danger" onclick="batchDeleteUsers()" id="batchDeleteBtn"
                            style="display:none;">
                            🗑️ 批量删除 (<span id="selectedCount">0</span>)
                        </button>
                        <div class="badge" style="padding:10px 20px;">
                            总用户: <span style="font-size:20px;font-weight:bold;" id="totalUsers">0</span>
                        </div>
                        <div class="badge" style="padding:10px 20px;">
                            管理员: <span style="font-size:20px;font-weight:bold;" id="adminCount">0</span>
                        </div>
                    </div>
                </div>

                <!-- 编辑用户信息模态框 -->
                <div id="editUserModal" class="modal" style="display:none;">
                    <div class="modal-content" style="max-width:500px;">
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
                            <h3 style="margin:0;color:#333;">✏️ 编辑用户信息</h3>
                            <button onclick="closeEditUserModal()"
                                style="background:none;border:none;font-size:24px;cursor:pointer;color:#999;">&times;</button>
                        </div>
                        <input type="hidden" id="editUserOpenid" />
                        <div style="margin-bottom:15px;">
                            <label style="display:block;margin-bottom:5px;color:#666;font-weight:500;">姓名</label>
                            <input type="text" id="editUserNickname" placeholder="请输入用户姓名"
                                style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;" />
                        </div>
                        <div style="margin-bottom:20px;">
                            <label style="display:block;margin-bottom:5px;color:#666;font-weight:500;">手机号</label>
                            <input type="text" id="editUserPhone" placeholder="请输入手机号"
                                style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;" />
                        </div>
                        <div style="display:flex;justify-content:flex-end;gap:10px;">
                            <button class="btn" onclick="closeEditUserModal()"
                                style="background:#f0f0f0;color:#666;">取消</button>
                            <button class="btn btn-primary" onclick="updateUserInfo()">保存</button>
                        </div>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th style="width:50px;">
                                <input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)" />
                            </th>
                            <th>头像</th>
                            <th>昵称</th>
                            <th>OpenID</th>
                            <th>电话</th>
                            <th>角色</th>
                            <th>注册时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userList">
                        <tr>
                            <td colspan="8" class="empty-state">
                                <div class="empty-icon">📭</div>
                                <div>加载中...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 机房管理标签页 -->
            <div class="tab-content" id="labsTab">
                <div class="toolbar">
                    <h2>机房列表</h2>
                    <button class="btn btn-primary" onclick="showAddLabModal()">➕ 添加机房</button>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>机房ID</th>
                            <th>机房名称</th>
                            <th>位置</th>
                            <th>设备数量</th>
                            <th>状态</th>
                            <th>备注</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="labList">
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div class="empty-icon">📭</div>
                                <div>加载中...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 工单管理标签页 -->
            <div class="tab-content" id="ordersTab">
                <div class="toolbar">
                    <h2>工单列表</h2>
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-number" id="pendingCount">0</div>
                        <div class="stat-label">待处理</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="processingCount">0</div>
                        <div class="stat-label">处理中</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="todayCount">0</div>
                        <div class="stat-label">今日报修</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalOrders">0</div>
                        <div class="stat-label">总工单</div>
                    </div>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>工单号</th>
                            <th>机房</th>
                            <th>设备</th>
                            <th>故障</th>
                            <th>报修人</th>
                            <th>状态</th>
                            <th>时间</th>
                        </tr>
                    </thead>
                    <tbody id="orderList">
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div class="empty-icon">📭</div>
                                <div>加载中...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 资产管理标签页 -->
            <div class="tab-content" id="assetsTab">
                <div class="toolbar">
                    <h2>资产列表</h2>
                    <div style="display:flex;gap:10px;">
                        <input type="text" id="assetSearch" placeholder="搜索资产编号或名称"
                            style="padding:10px;border:1px solid #ddd;border-radius:4px;width:200px;" />
                        <button class="btn btn-primary" onclick="searchAssets()">🔍 搜索</button>
                        <button class="btn btn-success" onclick="loadAssets()">🔄 刷新</button>
                        <button class="btn btn-success" onclick="showAddAssetModal()">➕ 添加资产</button>
                        <button class="btn btn-primary" onclick="downloadTemplate()">📄 下载模板</button>
                        <button class="btn btn-warning" onclick="showImportModal()">📥 批量导入</button>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin-bottom:20px;">
                    <div class="stat-card">
                        <div class="stat-number" id="totalAssets">0</div>
                        <div class="stat-label">总资产</div>
                    </div>
                    <div class="stat-card"
                        style="background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);color:white;">
                        <div class="stat-number" id="inUseAssets">0</div>
                        <div class="stat-label">在用</div>
                    </div>
                    <div class="stat-card"
                        style="background:linear-gradient(135deg, #f093fb 0%, #f5576c 100%);color:white;">
                        <div class="stat-number" id="idleAssets">0</div>
                        <div class="stat-label">闲置</div>
                    </div>
                    <div class="stat-card"
                        style="background:linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);color:white;">
                        <div class="stat-number" id="repairingAssets">0</div>
                        <div class="stat-label">维修中</div>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>资产编号</th>
                            <th>名称</th>
                            <th>分类</th>
                            <th>机房</th>
                            <th>状态</th>
                            <th>二维码</th>
                            <th>采购日期</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="assetList">
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div class="empty-icon">📭</div>
                                <div>加载中...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 借用管理标签页 -->
            <div class="tab-content" id="loansTab">
                <div class="toolbar">
                    <h2>借用记录</h2>
                    <div style="display:flex;gap:10px;">
                        <select id="loanStatusFilter" style="padding:10px;border:1px solid #ddd;border-radius:4px;"
                            onchange="loadLoans()">
                            <option value="">全部状态</option>
                            <option value="pending">待审批</option>
                            <option value="approved">借用中</option>
                            <option value="returned">已归还</option>
                            <option value="overdue">已逾期</option>
                        </select>
                        <button class="btn btn-success" onclick="loadLoans()">🔄 刷新</button>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>资产</th>
                            <th>借用人</th>
                            <th>用途</th>
                            <th>预计归还</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="loanList">
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div class="empty-icon">📭</div>
                                <div>加载中...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 盘点报废管理标签页 -->
            <div class="tab-content" id="inventoryTab">
                <div class="toolbar">
                    <h2>盘点与报废管理</h2>
                    <button class="btn btn-success" onclick="loadInventoryData()">🔄 刷新</button>
                </div>

                <!-- 盘点列表 -->
                <div style="margin-bottom:30px;">
                    <h3 style="margin-bottom:15px;color:#333;">📊 盘点记录</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>盘点ID</th>
                                <th>标题</th>
                                <th>时间范围</th>
                                <th>进度</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="inventoryList">
                            <tr>
                                <td colspan="5" class="empty-state">
                                    <div class="empty-icon">📋</div>
                                    <div>暂无盘点记录</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 报废申请列表 -->
                <div>
                    <h3 style="margin-bottom:15px;color:#333;">🗑️ 报废申请</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>资产</th>
                                <th>申请人</th>
                                <th>原因</th>
                                <th>申请时间</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="disposalList">
                            <tr>
                                <td colspan="6" class="empty-state">
                                    <div class="empty-icon">📋</div>
                                    <div>暂无报废申请</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 备件管理标签页 -->
            <div class="tab-content" id="sparepartsTab">
                <div class="toolbar">
                    <h2>备件管理</h2>
                    <div style="display:flex;gap:10px;">
                        <input type="text" id="partSearch" placeholder="搜索备件编号或名称"
                            style="padding:10px;border:1px solid #ddd;border-radius:4px;width:200px;" />
                        <select id="partCategoryFilter" style="padding:10px;border:1px solid #ddd;border-radius:4px;"
                            onchange="loadSpareParts()">
                            <option value="">全部分类</option>
                            <option value="存储设备">存储设备</option>
                            <option value="内存">内存</option>
                            <option value="外设">外设</option>
                            <option value="电源">电源</option>
                        </select>
                        <button class="btn btn-primary" onclick="searchParts()">🔍 搜索</button>
                        <button class="btn btn-success" onclick="loadSpareParts()">🔄 刷新</button>
                        <button class="btn btn-success" onclick="showAddPartModal()">➕ 添加备件</button>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin-bottom:20px;">
                    <div class="stat-card">
                        <div class="stat-number" id="totalParts">0</div>
                        <div class="stat-label">总备件种类</div>
                    </div>
                    <div class="stat-card"
                        style="background:linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);color:white;">
                        <div class="stat-number" id="lowStockParts">0</div>
                        <div class="stat-label">低库存备件</div>
                    </div>
                    <div class="stat-card"
                        style="background:linear-gradient(135deg, #52c41a 0%, #73d13d 100%);color:white;">
                        <div class="stat-number" id="totalStockValue">¥0</div>
                        <div class="stat-label">库存总价值</div>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>备件编号</th>
                            <th>名称</th>
                            <th>分类</th>
                            <th>当前库存</th>
                            <th>最低库存</th>
                            <th>单价</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="partList">
                        <tr>
                            <td colspan="7" class="empty-state">
                                <div class="empty-icon">📭</div>
                                <div>加载中...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 机房添加/编辑模态框 -->
    <div class="modal" id="labModal">
        <div class="modal-content">
            <div class="modal-header" id="labModalTitle">添加机房</div>
            <div class="form-group">
                <label>机房ID *</label>
                <input type="text" id="labId" placeholder="例如: A101" />
            </div>
            <div class="form-group">
                <label>机房名称 *</label>
                <input type="text" id="labName" placeholder="例如: A栋1楼实训室" />
            </div>
            <div class="form-group">
                <label>位置 *</label>
                <input type="text" id="labLocation" placeholder="例如: 教学楼A栋1楼" />
            </div>
            <div class="form-group">
                <label>设备数量</label>
                <input type="number" id="labDeviceCount" placeholder="0" />
            </div>
            <div class="form-group">
                <label>备注</label>
                <textarea id="labRemark" rows="3" placeholder="选填"></textarea>
            </div>
            <div class="modal-footer">
                <button class="btn" onclick="closeLabModal()">取消</button>
                <button class="btn btn-primary" onclick="saveLab()">保存</button>
            </div>
        </div>
    </div>

    <!-- 资产添加模态框 -->
    <div class="modal" id="assetModal">
        <div class="modal-content" style="max-width:600px;">
            <div class="modal-header">添加资产</div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">
                <div class="form-group">
                    <label>资产编号 *</label>
                    <input type="text" id="assetCode" placeholder="例如: PC-A101-001" />
                </div>
                <div class="form-group">
                    <label>资产名称 *</label>
                    <input type="text" id="assetName" placeholder="例如: 戴尔台式电脑" />
                </div>
                <div class="form-group">
                    <label>分类 *</label>
                    <select id="assetCategory">
                        <option value="">请选择</option>
                        <option value="6">台式电脑</option>
                        <option value="7">笔记本电脑</option>
                        <option value="8">一体机</option>
                        <option value="10">交换机</option>
                        <option value="11">路由器</option>
                        <option value="13">打印机</option>
                        <option value="16">投影仪</option>
                        <option value="17">电子白板</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>所属机房</label>
                    <select id="assetLab">
                        <option value="">请选择</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>品牌</label>
                    <input type="text" id="assetBrand" placeholder="例如: Dell" />
                </div>
                <div class="form-group">
                    <label>型号</label>
                    <input type="text" id="assetModel" placeholder="例如: OptiPlex 7090" />
                </div>
                <div class="form-group">
                    <label>采购价格</label>
                    <input type="number" id="assetPrice" placeholder="元" step="0.01" />
                </div>
                <div class="form-group">
                    <label>采购日期</label>
                    <input type="date" id="assetPurchaseDate" />
                </div>
            </div>
            <div class="form-group">
                <label>备注</label>
                <textarea id="assetRemark" rows="3" placeholder="选填"></textarea>
            </div>
            <div class="modal-footer">
                <button class="btn" onclick="closeAssetModal()">取消</button>
                <button class="btn btn-primary" onclick="saveAsset()">保存</button>
            </div>
        </div>
    </div>

    <!-- Excel批量导入模态框 -->
    <div class="modal" id="importModal">
        <div class="modal-content" style="max-width:500px;">
            <div class="modal-header">批量导入资产</div>
            <div class="form-group">
                <label>1. 下载Excel模板</label>
                <p style="color:#666;font-size:14px;margin:10px 0;">点击上方"📄 下载模板"按钮获取Excel模板文件</p>
            </div>
            <div class="form-group">
                <label>2. 填写资产数据</label>
                <p style="color:#666;font-size:14px;margin:10px 0;">在Excel中按模板格式填写资产信息</p>
            </div>
            <div class="form-group">
                <label>3. 上传Excel文件 *</label>
                <input type="file" id="excelFile" accept=".xlsx,.xls"
                    style="padding:10px;border:1px solid #ddd;border-radius:4px;width:100%;" />
            </div>
            <div id="importResult" style="display:none;margin-top:15px;padding:15px;border-radius:8px;"></div>
            <div class="modal-footer">
                <button class="btn" onclick="closeImportModal()">取消</button>
                <button class="btn btn-primary" onclick="importAssets()">开始导入</button>
            </div>
        </div>
    </div>

    <!-- 添加备件模态框 -->
    <div class="modal" id="addPartModal">
        <div class="modal-content">
            <div class="modal-header">添加备件</div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">
                <div class="form-group">
                    <label>备件编号 *</label>
                    <input type="text" id="newPartCode" placeholder="例如: HDD-001" />
                </div>
                <div class="form-group">
                    <label>备件名称 *</label>
                    <input type="text" id="newPartName" placeholder="例如: 机械硬盘1TB" />
                </div>
                <div class="form-group">
                    <label>分类</label>
                    <input type="text" id="newPartCategory" placeholder="例如: 存储设备" />
                </div>
                <div class="form-group">
                    <label>单价</label>
                    <input type="number" id="newPartPrice" placeholder="元" step="0.01" />
                </div>
                <div class="form-group">
                    <label>最低库存</label>
                    <input type="number" id="newPartMinStock" placeholder="0" />
                </div>
                <div class="form-group">
                    <label>存放位置</label>
                    <input type="text" id="newPartLocation" placeholder="例如: 仓库A-01" />
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn" onclick="closePartModal()">取消</button>
                <button class="btn btn-primary" onclick="savePart()">保存</button>
            </div>
        </div>
    </div>

    <!-- 入库/出库模态框 -->
    <div class="modal" id="stockModal">
        <div class="modal-content" style="max-width:400px;">
            <div class="modal-header" id="stockModalTitle">入库</div>
            <input type="hidden" id="stockPartId" />
            <input type="hidden" id="stockType" />
            <div class="form-group">
                <label>数量 *</label>
                <input type="number" id="stockQuantity" placeholder="请输入数量" />
            </div>
            <div class="form-group" id="unitPriceGroup">
                <label>单价</label>
                <input type="number" id="stockUnitPrice" placeholder="元" step="0.01" />
            </div>
            <div class="modal-footer">
                <button class="btn" onclick="closeStockModal()">取消</button>
                <button class="btn btn-primary" onclick="saveStock()">确定</button>
            </div>
        </div>
    </div>

    <!-- 二维码查看弹窗 -->
    <div id="qrCodeModal" class="modal">
        <div class="modal-content" style="max-width: 400px; text-align: center;">
            <div class="modal-header">
                <h2>📱 设备二维码</h2>
                <span class="close" onclick="closeModal('qrCodeModal')">&times;</span>
            </div>
            <div class="modal-body">
                <div id="qrCodeDisplay" style="margin: 20px auto; display: inline-block;"></div>
                <p id="qrCodeAssetInfo" style="margin-top: 10px; font-weight: bold; color: #333;"></p>
                <p id="qrCodeUrlDisplay" style="margin-top: 5px; font-size: 12px; color: #999; word-break: break-all;">
                </p>
            </div>
            <div class="modal-footer" style="justify-content: center; gap: 10px;">
                <button class="btn btn-primary" onclick="printQRCode()">🖨️ 打印</button>
                <button class="btn btn-success" onclick="downloadQRCodeImage()">💾 下载</button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
    <script>
        const API_BASE = window.location.origin + '/api';
        let currentKey = '';
        let editingLabId = null;
        let currentTab = 'users';

        // 登录
        function login() {
            const key = document.getElementById('adminKey').value;
            if (!key) {
                alert('请输入管理密钥');
                return;
            }
            currentKey = key;
            loadData();
        }

        // 退出
        function logout() {
            currentKey = '';
            document.getElementById('loginPanel').style.display = 'block';
            document.getElementById('header').style.display = 'none';
            document.getElementById('mainPanel').style.display = 'none';
        }

        // 加载数据
        async function loadData() {
            try {
                const response = await fetch(`${API_BASE}/admin/users?adminKey=${currentKey}`);
                const data = await response.json();

                if (data.code === 0) {
                    document.getElementById('loginPanel').style.display = 'none';
                    document.getElementById('header').style.display = 'flex';
                    document.getElementById('mainPanel').style.display = 'block';

                    loadUsers();
                    loadLabs();
                    loadOrders();
                } else {
                    alert(data.message || '登录失败');
                }
            } catch (error) {
                console.error('加载失败:', error);
                alert('网络错误，请稍后重试');
            }
        }

        // 切换标签页
        function switchTab(tab) {
            currentTab = tab;
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

            event.target.classList.add('active');
            document.getElementById(tab + 'Tab').classList.add('active');

            // 切换标签时加载对应数据
            if (tab === 'users') {
                loadUsers();
            } else if (tab === 'labs') {
                loadLabs();
            } else if (tab === 'orders') {
                loadOrders();
            } else if (tab === 'assets') {
                loadAssets();
                loadAssetStats();
            } else if (tab === 'qrcode') {
                loadQRCodeList();
            } else if (tab === 'loans') {
                loadLoans();
            } else if (tab === 'inventory') {
                loadInventoryData();
            } else if (tab === 'spareparts') {
                loadSpareParts();
                loadPartsStats();
            } else if (tab === 'config') {
                loadConfig();
                loadPartsStats();
            }
        }

        // 加载用户列表
        async function loadUsers() {
            try {
                const response = await fetch(`${API_BASE}/admin/users?adminKey=${currentKey}`);
                const data = await response.json();

                if (data.code === 0) {
                    renderUsers(data.data.list);
                }
            } catch (error) {
                console.error('加载用户失败:', error);
            }
        }

        // HTML转义函数 (防止XSS)
        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 渲染用户列表
        function renderUsers(users) {
            const tbody = document.getElementById('userList');

            if (!users || users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="empty-state"><div class="empty-icon">📭</div><div>暂无用户</div></td></tr>';
                return;
            }

            document.getElementById('totalUsers').textContent = users.length;
            document.getElementById('adminCount').textContent = users.filter(u => u.is_admin === 1).length;

            tbody.innerHTML = users.map(user => {
                const roleLabel = user.role === 'teacher' ? '👨‍🏫 教师' : (user.role === 'student' ? '👨‍🎓 学生' : '👤 普通用户');
                const roleBadgeClass = user.role === '教师' ? 'badge-admin' : (user.role === 'student' ? 'badge-warning' : 'badge-user');

                return `
                <tr>
                    <td><input type="checkbox" class="user-checkbox" value="${escapeHtml(user.openid)}" onchange="updateBatchDeleteButton()" /></td>
                    <td><img src="${escapeHtml(user.avatar) || '/images/default-avatar.png'}" alt="${escapeHtml(user.nickname)}" class="avatar" /></td>
                    <td>${escapeHtml(user.nickname) || '未设置'}</td>
                    <td style="font-family:monospace;font-size:12px;">${escapeHtml(user.openid)}</td>
                    <td>${escapeHtml(user.phone) || '-'}</td>
                    <td>
                        <select class="role-select" onchange="updateUserRole('${escapeHtml(user.openid)}', this.value)" style="padding:6px 12px;border:1px solid #d9d9d9;border-radius:6px;background:#fff;font-size:13px;">
                            <option value="user" ${user.role === 'user' ? 'selected' : ''}>👤 普通用户</option>
                            <option value="student" ${user.role === 'student' ? 'selected' : ''}>👨‍🎓 学生</option>
                            <option value="teacher" ${user.role === 'teacher' ? 'selected' : ''}>👨‍🏫 教师</option>
                            <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>👑 管理员</option>
                        </select>
                        ${user.role === 'admin' || user.is_admin === 1 ? '<span class="badge badge-admin" style="margin-left:8px;">👑 管理员</span>' : ''}
                    </td>
                    <td>${formatDate(user.created_at)}</td>
                    <td>
                        <div style="display:flex;gap:8px;flex-wrap:wrap;">
                            <button class="btn btn-primary btn-sm" onclick="editUser('${escapeHtml(user.openid)}', '${escapeHtml(user.nickname)}', '${escapeHtml(user.phone) || ''}')" style="background:#1677ff;">✏️ 编辑</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteUser('${escapeHtml(user.openid)}', '${escapeHtml(user.nickname)}')" style="background:#ff4d4f;">🗑️ 删除</button>
                        </div>
                    </td>
                </tr>
            `}).join('');
        }

        // 更新用户角色
        async function updateRole(openid, isAdmin) {
            if (!confirm(`确定要${isAdmin ? '设为管理员' : '取消管理员'}吗？`)) return;

            try {
                const response = await fetch(`${API_BASE}/admin/update-role`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ openid, isAdmin, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(data.message);
                    loadUsers();
                } else {
                    alert(data.message || '操作失败');
                }
            } catch (error) {
                console.error(error);
                alert('网络错误');
            }
        }

        // 更新用户身份角色 (Teacher/Student/User)
        async function updateUserRole(openid, role) {
            try {
                const response = await fetch(`${API_BASE}/admin/update-role`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ openid, role, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    // alert(data.message); // 成功时不弹窗，体验更好
                    console.log('角色更新成功');
                } else {
                    alert(data.message || '更新失败');
                    loadUsers(); // 失败还原
                }
            } catch (error) {
                console.error(error);
                alert('网络错误');
                loadUsers(); // 失败还原
            }
        }

        // 编辑用户信息
        function editUser(openid, nickname, phone) {
            document.getElementById('editUserOpenid').value = openid;
            document.getElementById('editUserNickname').value = nickname;
            document.getElementById('editUserPhone').value = phone || '';
            document.getElementById('editUserModal').style.display = 'flex';
        }

        function closeEditUserModal() {
            document.getElementById('editUserModal').style.display = 'none';
        }

        // 更新用户信息
        async function updateUserInfo() {
            const openid = document.getElementById('editUserOpenid').value;
            const nickname = document.getElementById('editUserNickname').value.trim();
            const phone = document.getElementById('editUserPhone').value.trim();

            if (!nickname) {
                alert('姓名不能为空');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/admin/update-user-info`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ openid, nickname, phone, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(data.message);
                    closeEditUserModal();
                    loadUsers();
                } else {
                    alert(data.message || '更新失败');
                }
            } catch (error) {
                console.error(error);
                alert('网络错误');
            }
        }

        // 删除用户
        async function deleteUser(openid, nickname) {
            if (!confirm(`确定要删除用户 "${nickname}" 吗？\n\n此操作将删除该用户的所有数据，包括报修记录、借用记录等，且无法恢复！`)) return;

            // 二次确认
            if (!confirm(`再次确认：您确定要删除用户 "${nickname}" 吗？`)) return;

            try {
                const response = await fetch(`${API_BASE}/admin/delete-user`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ openid, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert('用户删除成功！');
                    loadUsers();
                } else {
                    alert(data.message || '删除失败');
                }
            } catch (error) {
                console.error(error);
                alert('网络错误');
            }
        }

        // 全选/取消全选
        function toggleSelectAll(checkbox) {
            const checkboxes = document.querySelectorAll('.user-checkbox');
            checkboxes.forEach(cb => cb.checked = checkbox.checked);
            updateBatchDeleteButton();
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkedBoxes = document.querySelectorAll('.user-checkbox:checked');
            const count = checkedBoxes.length;
            const btn = document.getElementById('batchDeleteBtn');
            const countSpan = document.getElementById('selectedCount');

            if (count > 0) {
                btn.style.display = 'block';
                countSpan.textContent = count;
            } else {
                btn.style.display = 'none';
                document.getElementById('selectAll').checked = false;
            }
        }

        // 批量删除用户
        async function batchDeleteUsers() {
            const checkedBoxes = document.querySelectorAll('.user-checkbox:checked');
            const openids = Array.from(checkedBoxes).map(cb => cb.value);

            if (openids.length === 0) {
                alert('请先选择要删除的用户');
                return;
            }

            if (!confirm(`确定要删除选中的 ${openids.length} 个用户吗？\n\n此操作将删除这些用户的所有数据，包括报修记录、借用记录等，且无法恢复！`)) {
                return;
            }

            // 二次确认
            if (!confirm(`再次确认：您确定要批量删除 ${openids.length} 个用户吗？`)) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/admin/delete-users-batch`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ openids, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(`成功删除 ${data.data.deletedCount} 个用户！`);
                    document.getElementById('selectAll').checked = false;
                    loadUsers();
                } else {
                    alert(data.message || '批量删除失败');
                }
            } catch (error) {
                console.error(error);
                alert('网络错误');
            }
        }

        // 加载机房列表
        async function loadLabs() {
            try {
                const response = await fetch(`${API_BASE}/admin/labs?adminKey=${currentKey}`);
                const data = await response.json();

                if (data.code === 0) {
                    renderLabs(data.data.list);
                }
            } catch (error) {
                console.error('加载机房失败:', error);
            }
        }

        // 渲染机房列表
        function renderLabs(labs) {
            const tbody = document.getElementById('labList');

            if (!labs || labs.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><div class="empty-icon">📭</div><div>暂无机房</div></td></tr>';
                return;
            }

            tbody.innerHTML = labs.map(lab => `
                <tr>
                    <td><strong>${lab.id}</strong></td>
                    <td>${lab.name}</td>
                    <td>${lab.location}</td>
                    <td>${lab.device_count || 0}</td>
                    <td><span class="badge ${lab.status === 'active' ? 'badge-completed' : 'badge-pending'}">${lab.status === 'active' ? '正常' : '维护中'}</span></td>
                    <td>${lab.remark || '-'}</td>
                    <td>
                        <button class="btn btn-warning btn-sm" onclick="editLab('${lab.id}')">编辑</button>
                        <button class="btn btn-danger btn-sm" onclick="deleteLab('${lab.id}')">删除</button>
                        <button class="btn btn-info btn-sm" onclick="showLabQRCode('${lab.id}', '${lab.name}')">生成二维码</button>
                    </td>
                </tr>
            `).join('');
        }

        // 显示添加机房模态框
        function showAddLabModal() {
            editingLabId = null;
            document.getElementById('labModalTitle').textContent = '添加机房';
            document.getElementById('labId').value = '';
            document.getElementById('labId').disabled = false;
            document.getElementById('labName').value = '';
            document.getElementById('labLocation').value = '';
            document.getElementById('labDeviceCount').value = '';
            document.getElementById('labRemark').value = '';
            document.getElementById('labModal').classList.add('show');
        }

        // 编辑机房
        async function editLab(labId) {
            try {
                const response = await fetch(`${API_BASE}/lab/info?labId=${labId}`);
                const data = await response.json();

                if (data.code === 0) {
                    editingLabId = labId;
                    document.getElementById('labModalTitle').textContent = '编辑机房';
                    document.getElementById('labId').value = data.data.id;
                    document.getElementById('labId').disabled = true;
                    document.getElementById('labName').value = data.data.name;
                    document.getElementById('labLocation').value = data.data.location;
                    document.getElementById('labDeviceCount').value = data.data.device_count || '';
                    document.getElementById('labRemark').value = data.data.remark || '';
                    document.getElementById('labModal').classList.add('show');
                }
            } catch (error) {
                alert('加载机房信息失败');
            }
        }

        // 保存机房
        async function saveLab() {
            const labId = document.getElementById('labId').value.trim();
            const name = document.getElementById('labName').value.trim();
            const location = document.getElementById('labLocation').value.trim();
            const deviceCount = document.getElementById('labDeviceCount').value;
            const remark = document.getElementById('labRemark').value.trim();

            if (!labId || !name || !location) {
                alert('请填写必填项');
                return;
            }

            const url = editingLabId ? `${API_BASE}/admin/lab/update` : `${API_BASE}/admin/lab/add`;

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ labId, name, location, deviceCount, remark, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(data.message);
                    closeLabModal();
                    loadLabs();
                } else {
                    alert(data.message);
                }
            } catch (error) {
                alert('网络错误');
            }
        }

        // 删除机房
        async function deleteLab(labId) {
            if (!confirm('确定要删除该机房吗？如果有关联的报修记录将无法删除。')) return;

            try {
                const response = await fetch(`${API_BASE}/admin/lab/delete`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ labId, adminKey: currentKey })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(data.message);
                    loadLabs();
                } else {
                    alert(data.message);
                }
            } catch (error) {
                alert('网络错误');
            }
        }

        // 关闭机房模态框
        function closeLabModal() {
            document.getElementById('labModal').classList.remove('show');
        }

        // 加载工单列表
        async function loadOrders() {
            try {
                // 加载统计数据
                const statsResponse = await fetch(`${API_BASE}/repair/stats`);
                const statsData = await statsResponse.json();

                if (statsData.code === 0) {
                    document.getElementById('pendingCount').textContent = statsData.data.pending || 0;
                    document.getElementById('processingCount').textContent = statsData.data.processing || 0;
                    document.getElementById('todayCount').textContent = statsData.data.today || 0;
                    document.getElementById('totalOrders').textContent = statsData.data.total || 0;
                }

                // 加载工单列表 - 使用adminKey绕过权限检查
                const ordersResponse = await fetch(`${API_BASE}/repair/list?adminKey=${currentKey}&page=1&pageSize=50`);
                const ordersData = await ordersResponse.json();

                if (ordersData.code === 0) {
                    renderOrders(ordersData.data.list);
                } else {
                    console.error('加载工单失败:', ordersData.message);
                    document.getElementById('orderList').innerHTML = `
                        <tr><td colspan="7" class="empty-state">
                            <div class="empty-icon">❌</div>
                            <div>加载失败: ${ordersData.message || '未知错误'}</div>
                        </td></tr>
                    `;
                }
            } catch (error) {
                console.error('加载工单失败:', error);
                document.getElementById('orderList').innerHTML = `
                    <tr><td colspan="7" class="empty-state">
                        <div class="empty-icon">❌</div>
                        <div>网络错误，请刷新重试</div>
                    </td></tr>
                `;
            }
        }

        // 渲染工单列表
        function renderOrders(orders) {
            const tbody = document.getElementById('orderList');

            if (!orders || orders.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><div class="empty-icon">📭</div><div>暂无工单</div></td></tr>';
                return;
            }

            const statusMap = {
                'pending': { text: '待处理', class: 'badge-pending' },
                'processing': { text: '处理中', class: 'badge-processing' },
                'completed': { text: '已完成', class: 'badge-completed' },
                'rejected': { text: '已拒绝', class: 'badge-rejected' }
            };

            tbody.innerHTML = orders.map(order => {
                const status = statusMap[order.status] || { text: order.status, class: '' };
                return `
                    <tr>
                        <td><strong>#${order.id}</strong></td>
                        <td>${order.lab_name}</td>
                        <td>${order.device_type_name}</td>
                        <td>${order.fault_type_name}</td>
                        <td>${order.user_name || '-'}</td>
                        <td><span class="badge ${status.class}">${status.text}</span></td>
                        <td>${formatDate(order.created_at)}</td>
                    </tr>
                `;
            }).join('');
        }

        // 格式化日期
        function formatDate(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 点击模态框外部关闭
        window.onclick = function (event) {
            if (event.target.classList.contains('modal')) {
                event.target.classList.remove('show');
            }
        }

        // ========== 资产管理相关函数 ==========

        // 加载资产列表
        async function loadAssets() {
            try {
                const keyword = document.getElementById('assetSearch').value || '';
                const url = `${API_BASE}/assets?keyword=${encodeURIComponent(keyword)}`;

                const response = await fetch(url);
                const data = await response.json();

                if (data.code === 0) {
                    renderAssets(data.data.list);
                    loadAssetStats();
                }
            } catch (error) {
                console.error('加载资产失败:', error);
            }
        }

        // 搜索资产
        function searchAssets() {
            loadAssets();
        }

        // 加载资产统计
        async function loadAssetStats() {
            try {
                const response = await fetch(`${API_BASE}/asset/stats`);
                const data = await response.json();

                if (data.code === 0) {
                    const stats = data.data;
                    document.getElementById('totalAssets').textContent = stats.totalCount || 0;
                    document.getElementById('inUseAssets').textContent = stats.inUseCount || 0;
                    document.getElementById('idleAssets').textContent = stats.idleCount || 0;
                    document.getElementById('repairingAssets').textContent = stats.repairingCount || 0;
                }
            } catch (error) {
                console.error('加载资产统计失败:', error);
            }
        }

        let allAssets = [];

        // 渲染资产列表
        function renderAssets(assets) {
            allAssets = assets || []; // 更新全局资产列表
            const tbody = document.getElementById('assetList');
            tbody.innerHTML = '';

            if (!assets || assets.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="8" class="empty-state">
                            <div class="empty-icon">📭</div>
                            <div>暂无设备数据</div>
                        </td>
                    </tr>
                `;
                return;
            }

            const statusMap = {
                'in_use': { text: '在用', class: 'badge-completed' },
                'active': { text: '在用', class: 'badge-completed' }, // 兼容 active 状态
                'idle': { text: '闲置', class: 'badge-pending' },
                'repairing': { text: '维修中', class: 'badge-processing' },
                'scrapped': { text: '已报废', class: 'badge-rejected' }
            };

            assets.forEach(asset => {
                const tr = document.createElement('tr');
                const status = statusMap[asset.status] || { text: asset.status, class: 'badge-secondary' };

                // QR Code status and button
                let qrCodeHtml = '';
                if (asset.qr_code) {
                    qrCodeHtml = `
                        <button class="btn btn-sm btn-outline-primary" onclick="showQRCodeModal(${asset.id})">
                            <span style="font-size:12px;">📱</span> 查看
                        </button>
                    `;
                } else {
                    qrCodeHtml = `
                        <button class="btn btn-sm btn-outline-secondary" onclick="generateAndShowQR(${asset.id})">
                            <span style="font-size:12px;">➕</span> 生成
                        </button>
                    `;
                }

                tr.innerHTML = `
                    <td>${asset.asset_code || '-'}</td>
                    <td>${asset.name}</td>
                    <td>${asset.category || asset.category_name || '-'}</td>
                    <td>${asset.lab_name || '-'}</td>
                    <td><span class="badge ${status.class}">${status.text}</span></td>
                    <td>${qrCodeHtml}</td>
                    <td>${formatDate(asset.purchase_date)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editAsset(${asset.id})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteAsset(${asset.id})">删除</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 显示添加资产模态框
        async function showAddAssetModal() {
            // 清空表单
            document.getElementById('assetCode').value = '';
            document.getElementById('assetName').value = '';
            document.getElementById('assetCategory').value = '';
            document.getElementById('assetLab').value = '';
            document.getElementById('assetBrand').value = '';
            document.getElementById('assetModel').value = '';
            document.getElementById('assetPrice').value = '';
            document.getElementById('assetPurchaseDate').value = '';
            document.getElementById('assetRemark').value = '';

            // 加载机房列表到下拉框
            try {
                const response = await fetch(`${API_BASE}/lab/list`);
                const data = await response.json();
                if (data.code === 0) {
                    const labSelect = document.getElementById('assetLab');
                    labSelect.innerHTML = '<option value="">请选择</option>' +
                        (data.data.list || []).map(lab =>
                            `<option value="${lab.id}">${lab.name}</option>`
                        ).join('');
                }
            } catch (error) {
                console.error('加载机房列表失败:', error);
            }

            document.getElementById('assetModal').classList.add('show');
        }

        // 保存资产
        async function saveAsset() {
            const assetCode = document.getElementById('assetCode').value.trim();
            const name = document.getElementById('assetName').value.trim();
            const categoryId = document.getElementById('assetCategory').value;

            if (!assetCode || !name || !categoryId) {
                alert('请填写必填项：资产编号、名称和分类');
                return;
            }

            const assetData = {
                assetCode,
                name,
                categoryId: parseInt(categoryId),
                labId: document.getElementById('assetLab').value || null,
                brand: document.getElementById('assetBrand').value || null,
                model: document.getElementById('assetModel').value || null,
                purchasePrice: document.getElementById('assetPrice').value ? parseFloat(document.getElementById('assetPrice').value) : null,
                purchaseDate: document.getElementById('assetPurchaseDate').value || null,
                remark: document.getElementById('assetRemark').value || null,
                adminKey: currentKey
            };

            try {
                const response = await fetch(`${API_BASE}/admin/asset/add`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(assetData)
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert('添加成功！');
                    closeAssetModal();
                    loadAssets();
                } else {
                    alert(data.message || '添加失败');
                }
            } catch (error) {
                console.error('添加资产失败:', error);
                alert('网络错误');
            }
        }

        // 关闭资产模态框
        function closeAssetModal() {
            document.getElementById('assetModal').classList.remove('show');
        }

        // ========== Excel批量导入相关函数 ==========

        // 下载Excel模板
        function downloadTemplate() {
            window.open(`${API_BASE}/admin/asset/template?adminKey=${currentKey}`, '_blank');
        }

        // 显示导入模态框
        function showImportModal() {
            document.getElementById('excelFile').value = '';
            document.getElementById('importResult').style.display = 'none';
            document.getElementById('importModal').classList.add('show');
        }

        // 批量导入资产
        async function importAssets() {
            const fileInput = document.getElementById('excelFile');
            const file = fileInput.files[0];

            if (!file) {
                alert('请选择Excel文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('adminKey', currentKey);

            const resultDiv = document.getElementById('importResult');
            resultDiv.style.display = 'block';
            resultDiv.style.background = '#f0f0f0';
            resultDiv.innerHTML = '<p>正在导入，请稍候...</p>';

            try {
                const response = await fetch(`${API_BASE}/admin/asset/import`, {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                if (data.code === 0) {
                    const result = data.data;
                    let html = `
                    <h4 style="margin:0 0 10px 0;color:#52c41a;">✅ 导入完成</h4>
                        <p>总数: ${result.total} | 成功: ${result.successCount} | 失败: ${result.failCount}</p>
                `;

                    if (result.errors && result.errors.length > 0) {
                        html += '<p style="color:#ff4d4f;margin-top:10px;">错误信息（前10条）：</p>';
                        html += '<ul style="margin:5px 0;padding-left:20px;font-size:14px;">';
                        result.errors.forEach(err => {
                            html += `<li style="color:#ff4d4f;">${err}</li>`;
                        });
                        html += '</ul>';
                    }

                    resultDiv.style.background = '#f6ffed';
                    resultDiv.innerHTML = html;

                    // 刷新资产列表
                    loadAssets();
                } else {
                    resultDiv.style.background = '#fff2f0';
                    resultDiv.innerHTML = `<p style="color:#ff4d4f;">❌ ${data.message}</p>`;
                }
            } catch (error) {
                console.error('导入失败:', error);
                resultDiv.style.background = '#fff2f0';
                resultDiv.innerHTML = '<p style="color:#ff4d4f;">❌ 网络错误，请重试</p>';
            }
        }

        // 关闭导入模态框
        function closeImportModal() {
            document.getElementById('importModal').classList.remove('show');
        }

        // ========== 备件管理相关函数 ==========

        // 加载备件列表
        async function loadSpareParts() {
            try {
                const keyword = document.getElementById('partSearch').value;
                const category = document.getElementById('partCategoryFilter').value;
                const url = `${API_BASE}/spare-parts?keyword=${keyword}&category=${category}`;

                const response = await fetch(url);
                const data = await response.json();

                if (data.code === 0) {
                    renderSpareParts(data.data.list);
                    loadPartsStats();
                }
            } catch (error) {
                console.error('加载备件失败:', error);
            }
        }

        function searchParts() {
            loadSpareParts();
        }

        // 渲染备件列表
        function renderSpareParts(parts) {
            const tbody = document.getElementById('partList');

            if (!parts || parts.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><div class="empty-icon">📭</div><div>暂无备件</div></td></tr>';
                return;
            }

            tbody.innerHTML = parts.map(part => {
                const lowStock = part.current_stock < part.min_stock;
                const stockClass = lowStock ? 'style="color:#ff4d4f;font-weight:bold;"' : '';

                return `
                    <tr>
                        <td><strong>${part.part_code}</strong></td>
                        <td>${part.name}</td>
                        <td>${part.category || '-'}</td>
                        <td ${stockClass}>${part.current_stock || 0}</td>
                        <td>${part.min_stock || 0}</td>
                        <td>¥${part.unit_price ? parseFloat(part.unit_price).toFixed(2) : '-'}</td>
                        <td>
                            <button class="btn btn-success" style="padding:5px 10px;font-size:12px;" onclick="showStockIn(${part.id})">入库</button>
                            <button class="btn btn-warning" style="padding:5px 10px;font-size:12px;" onclick="showStockOut(${part.id})">出库</button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 加载统计
        async function loadPartsStats() {
            try {
                const response = await fetch(`${API_BASE}/admin/spare-parts/stats?adminKey=${currentKey}`);
                const data = await response.json();

                if (data.code === 0) {
                    document.getElementById('totalParts').textContent = data.data.totalCount;
                    document.getElementById('lowStockParts').textContent = data.data.lowStockCount;
                    document.getElementById('totalStockValue').textContent = '¥' + parseFloat(data.data.totalValue || 0).toFixed(2);
                }
            } catch (error) {
                console.error('加载统计失败:', error);
            }
        }

        // 显示添加备件模态框
        function showAddPartModal() {
            document.getElementById('newPartCode').value = '';
            document.getElementById('newPartName').value = '';
            document.getElementById('newPartCategory').value = '';
            document.getElementById('newPartPrice').value = '';
            document.getElementById('newPartMinStock').value = '';
            document.getElementById('newPartLocation').value = '';
            document.getElementById('addPartModal').classList.add('show');
        }

        // 保存备件
        async function savePart() {
            const partCode = document.getElementById('newPartCode').value.trim();
            const name = document.getElementById('newPartName').value.trim();

            if (!partCode || !name) {
                alert('请填写备件编号和名称');
                return;
            }

            const partData = {
                partCode,
                name,
                category: document.getElementById('newPartCategory').value,
                unitPrice: document.getElementById('newPartPrice').value || null,
                minStock: document.getElementById('newPartMinStock').value || 0,
                location: document.getElementById('newPartLocation').value,
                adminKey: currentKey
            };

            try {
                const response = await fetch(`${API_BASE}/admin/spare-part/add`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(partData)
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert('添加成功！');
                    closePartModal();
                    loadSpareParts();
                } else {
                    alert(data.message || '添加失败');
                }
            } catch (error) {
                alert('网络错误');
            }
        }

        function closePartModal() {
            document.getElementById('addPartModal').classList.remove('show');
        }

        // 显示入库模态框
        function showStockIn(partId) {
            document.getElementById('stockPartId').value = partId;
            document.getElementById('stockType').value = 'in';
            document.getElementById('stockModalTitle').textContent = '入库';
            document.getElementById('stockQuantity').value = '';
            document.getElementById('stockUnitPrice').value = '';
            document.getElementById('unitPriceGroup').style.display = 'block';
            document.getElementById('stockModal').classList.add('show');
        }

        // 显示出库模态框
        function showStockOut(partId) {
            document.getElementById('stockPartId').value = partId;
            document.getElementById('stockType').value = 'out';
            document.getElementById('stockModalTitle').textContent = '出库';
            document.getElementById('stockQuantity').value = '';
            document.getElementById('unitPriceGroup').style.display = 'none';
            document.getElementById('stockModal').classList.add('show');
        }

        // 保存库存操作
        async function saveStock() {
            const partId = document.getElementById('stockPartId').value;
            const type = document.getElementById('stockType').value;
            const quantity = document.getElementById('stockQuantity').value;
            const unitPrice = document.getElementById('stockUnitPrice').value;

            if (!quantity) {
                alert('请输入数量');
                return;
            }

            const url = type === 'in' ? `${API_BASE}/admin/spare-part/stock-in` : `${API_BASE}/admin/spare-part/stock-out`;
            const stockData = {
                partId: parseInt(partId),
                quantity: parseInt(quantity),
                unitPrice: unitPrice ? parseFloat(unitPrice) : null,
                adminKey: currentKey
            };

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(stockData)
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(type === 'in' ? '入库成功！' : '出库成功！');
                    closeStockModal();
                    loadSpareParts();
                } else {
                    alert(data.message || '操作失败');
                }
            } catch (error) {
                alert('网络错误');
            }
        }

        function closeStockModal() {
            document.getElementById('stockModal').classList.remove('show');
        }

        // 审批借用申请
        async function approveLoan(loanId, approve) {
            const action = approve ? '通过' : '拒绝';
            let rejectReason = '';

            if (!approve) {
                rejectReason = prompt('请输入拒绝原因：');
                if (!rejectReason) return;
            }

            if (!confirm(`确定${action}此借用申请？`)) return;

            try {
                const response = await fetch(`${API_BASE}/admin/asset/loan/approve`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        loanId,
                        approve,
                        rejectReason,
                        adminOpenid: 'admin',
                        adminName: '管理员',
                        adminKey: currentKey
                    })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert(`${action}成功！`);
                    loadLoans(); // 刷新列表
                } else {
                    alert(data.message || `${action}失败`);
                }
            } catch (error) {
                alert('网络错误');
                console.error('审批失败:', error);
            }
        }

        // 查看资产详情
        async function viewAssetDetail(assetId) {
            try {
                const response = await fetch(`${API_BASE}/asset/${assetId}`);
                const data = await response.json();

                if (data.code === 0) {
                    const asset = data.data;
                    const statusMap = {
                        'in_use': '在用',
                        'idle': '闲置',
                        'repairing': '维修中',
                        'scrapped': '已报废'
                    };

                    let detailHtml = `
                        <h3 style="margin:0 0 20px 0;">资产详情</h3>
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:15px;">
                            <div><strong>资产编号：</strong>${asset.asset_code}</div>
                            <div><strong>资产名称：</strong>${asset.name}</div>
                            <div><strong>分类：</strong>${asset.category_name || '-'}</div>
                            <div><strong>所属机房：</strong>${asset.lab_name || '-'}</div>
                            <div><strong>状态：</strong>${statusMap[asset.status] || asset.status}</div>
                            <div><strong>品牌：</strong>${asset.brand || '-'}</div>
                            <div><strong>型号：</strong>${asset.model || '-'}</div>
                            <div><strong>采购日期：</strong>${asset.purchase_date ? asset.purchase_date.split('T')[0] : '-'}</div>
                            <div><strong>采购价格：</strong>${asset.purchase_price ? '¥' + asset.purchase_price : '-'}</div>
                            <div><strong>供应商：</strong>${asset.supplier || '-'}</div>
                        </div>
                        ${asset.remark ? `<div style="margin-top:15px;"><strong>备注：</strong><br/>${asset.remark}</div>` : ''}
                        ${asset.repairHistory && asset.repairHistory.length > 0 ?
                            `<div style="margin-top:20px;">
                                <strong>维修历史（${asset.repairHistory.length}条）：</strong>
                                <div style="max-height:200px;overflow-y:auto;margin-top:10px;">
                                    ${asset.repairHistory.slice(0, 5).map(r => `
                                        <div style="padding:8px;background:#f5f5f5;margin-bottom:8px;border-radius:4px;">
                                            <div>工单#${r.id} - ${r.description}</div>
                                            <div style="font-size:12px;color:#666;">${r.created_at}</div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>` : ''
                        }
                    `;

                    // 使用浏览器confirm来显示（简单方式）
                    // 或者创建自定义模态框
                    const modal = document.createElement('div');
                    modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:10000;';
                    modal.innerHTML = `
                        <div style="background:white;padding:30px;border-radius:12px;max-width:800px;max-height:80vh;overflow-y:auto;box-shadow:0 4px 20px rgba(0,0,0,0.3);">
                            ${detailHtml}
                            <button onclick="this.closest('div').parentElement.remove()" 
                                style="margin-top:20px;padding:10px 30px;background:#1677ff;color:white;border:none;border-radius:6px;cursor:pointer;">
                                关闭
                            </button>
                        </div>
                    `;
                    document.body.appendChild(modal);
                    modal.onclick = (e) => { if (e.target === modal) modal.remove(); };
                } else {
                    alert('获取资产详情失败：' + data.message);
                }
            } catch (error) {
                console.error('获取资产详情失败:', error);
                alert('获取资产详情失败，请重试');
            }
        }

        // ========== 借用管理相关函数 ==========

        // 加载借用列表
        async function loadLoans() {
            try {
                const status = document.getElementById('loanStatusFilter').value;
                const url = `${API_BASE}/asset/loans${status ? '?status=' + status : ''}`;

                const response = await fetch(url);
                const data = await response.json();

                if (data.code === 0) {
                    renderLoans(data.data.list);
                }
            } catch (error) {
                console.error('加载借用记录失败:', error);
            }
        }

        // 渲染借用列表
        function renderLoans(loans) {
            const tbody = document.getElementById('loanList');

            if (!loans || loans.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><div class="empty-icon">📭</div><div>暂无借用记录</div></td></tr>';
                return;
            }

            const statusMap = {
                'pending': { text: '待审批', class: 'badge-pending' },
                'approved': { text: '借用中', class: 'badge-processing' },
                'rejected': { text: '已拒绝', class: 'badge-rejected' },
                'returned': { text: '已归还', class: 'badge-completed' },
                'overdue': { text: '已逾期', class: 'badge-rejected' }
            };

            tbody.innerHTML = loans.map(loan => {
                const status = statusMap[loan.status] || { text: loan.status, class: '' };
                const expectedDate = loan.expected_return_date ? loan.expected_return_date.split('T')[0] : '-';

                return `
                    <tr>
                        <td><strong>#${loan.id}</strong></td>
                        <td>${loan.asset_name || loan.asset_code}</td>
                        <td>${loan.borrower_name}</td>
                        <td>${loan.purpose || '-'}</td>
                        <td>${expectedDate}</td>
                        <td><span class="badge ${status.class}">${status.text}</span></td>
                        <td>
                            ${loan.status === 'pending' ? `<button class="btn btn-success" style="padding:5px 10px;font-size:12px;margin-right:5px;" onclick="approveLoan(${loan.id}, true)">通过</button><button class="btn btn-danger" style="padding:5px 10px;font-size:12px;" onclick="approveLoan(${loan.id}, false)">拒绝</button>` : '-'}
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // ========== 盘点报废管理相关函数 ==========

        // 加载盘点和报废数据
        async function loadInventoryData() {
            loadInventoryList();
            loadDisposalList();
        }

        // 加载盘点列表
        async function loadInventoryList() {
            try {
                const response = await fetch(`${API_BASE}/inventory/list`);
                const data = await response.json();

                if (data.code === 0) {
                    renderInventory(data.data.list);
                }
            } catch (error) {
                console.error('加载盘点记录失败:', error);
            }
        }

        // 渲染盘点列表
        function renderInventory(inventories) {
            const tbody = document.getElementById('inventoryList');

            if (!inventories || inventories.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="empty-state"><div class="empty-icon">📋</div><div>暂无盘点记录</div></td></tr>';
                return;
            }

            tbody.innerHTML = inventories.map(inv => {
                const dateRange = `${inv.start_date || '-'} 至 ${inv.end_date || '-'}`;
                const progress = inv.total_count > 0 ? `${inv.checked_count}/${inv.total_count}` : '-';

                return `
                    <tr>
                        <td><strong>#${inv.id}</strong></td>
                        <td>${inv.title}</td>
                        <td>${dateRange}</td>
                        <td>${progress}</td>
                        <td><span class="badge">${inv.status}</span></td>
                    </tr>
                `;
            }).join('');
        }

        // 加载报废列表
        async function loadDisposalList() {
            try {
                const response = await fetch(`${API_BASE}/asset/disposal/list`);
                const data = await response.json();

                if (data.code === 0) {
                    renderDisposal(data.data.list);
                }
            } catch (error) {
                console.error('加载报废申请失败:', error);
            }
        }

        // 渲染报废列表
        function renderDisposal(disposals) {
            const tbody = document.getElementById('disposalList');

            if (!disposals || disposals.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="empty-state"><div class="empty-icon">📋</div><div>暂无报废申请</div></td></tr>';
                return;
            }

            const statusMap = {
                'pending': { text: '待审批', class: 'badge-pending' },
                'approved': { text: '已批准', class: 'badge-completed' },
                'rejected': { text: '已拒绝', class: 'badge-rejected' }
            };

            tbody.innerHTML = disposals.map(disp => {
                const status = statusMap[disp.status] || { text: disp.status, class: '' };

                return `
                    <tr>
                        <td><strong>#${disp.id}</strong></td>
                        <td>${disp.asset_name} (${disp.asset_code})</td>
                        <td>${disp.applicant_name}</td>
                        <td>${disp.reason}</td>
                        <td>${new Date(disp.created_at).toLocaleString()}</td>
                        <td><span class="badge ${status.class}">${status.text}</span></td>
                    </tr>
                `;
            }).join('');
        }

        // ========== 二维码生成相关函数 ==========

        // 显示二维码模态框
        function showQRCode(title, content) {
            // 创建或获取模态框
            let modal = document.getElementById('wxaQRCodeModal');
            if (!modal) {
                modal = document.createElement('div');
                modal.id = 'wxaQRCodeModal';
                modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:10000;';
                modal.innerHTML = `
                    <div style="background:white;padding:30px;border-radius:12px;text-align:center;box-shadow:0 4px 20px rgba(0,0,0,0.3);">
                        <h3 id="wxaQrTitle" style="margin-bottom:20px;"></h3>
                        <div id="wxaQrContainer" style="display:flex;justify-content:center;margin-bottom:20px;"></div>
                        <div id="wxaQrContent" style="margin-bottom:20px;color:#666;font-size:12px;word-break:break-all;max-width:300px;"></div>
                        <button onclick="document.getElementById('wxaQRCodeModal').style.display='none'" 
                            style="padding:8px 30px;background:#1677ff;color:white;border:none;border-radius:6px;cursor:pointer;">
                            关闭
                        </button>
                    </div>
                `;
                document.body.appendChild(modal);
            }

            document.getElementById('wxaQrTitle').textContent = title;

            const container = document.getElementById('wxaQrContainer');
            container.innerHTML = ''; // Clear previous content

            // 构建标准二维码URL (扫普通链接打开小程序)
            let url = 'https://你的域名/pages/index/index';
            if (content.labId) {
                url += `?labId=${content.labId}`;
            } else if (content.assetId) {
                url += `?assetId=${content.assetId}`;
            }

            document.getElementById('wxaQrContent').textContent = '链接: ' + url;

            modal.style.display = 'flex';

            // 生成标准二维码
            new QRCode(container, {
                text: url,
                width: 200,
                height: 200,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        // 为机房生成二维码
        function showLabQRCode(id, name) {
            showQRCode(name + ' - 报修码', { labId: id });
        }

        // 为资产生成二维码
        function showAssetQRCode(code, name) {
            showQRCode(name + ' - 资产码', { assetId: code }); // 使用asset_code作为ID
        }

        // ========== 系统配置相关函数 ==========

        // 加载配置
        async function loadConfig() {
            try {
                const response = await fetch(`${API_BASE}/admin/config?adminKey=${currentKey}\u0026group=wechat`);
                const data = await response.json();

                if (data.code === 0) {
                    const config = data.data;
                    document.getElementById('wechat_app_id').value = config.wechat_app_id?.value || '';
                    document.getElementById('wechat_app_secret').value = config.wechat_app_secret?.value || '';
                    document.getElementById('template_loan_apply').value = config.wechat_template_loan_apply?.value || '';
                    document.getElementById('template_loan_approve').value = config.wechat_template_loan_approve?.value || '';
                    document.getElementById('template_loan_reminder').value = config.wechat_template_loan_reminder?.value || '';
                    document.getElementById('template_repair_submit').value = config.wechat_template_repair_submit?.value || '';
                    document.getElementById('template_repair_accept').value = config.wechat_template_repair_accept?.value || '';
                    document.getElementById('template_repair_complete').value = config.wechat_template_repair_complete?.value || '';
                    document.getElementById('template_admin_repair_notify').value = config.wechat_template_admin_repair_notify?.value || '';
                    // 加载模板内容（JSON）
                    window.currentTemplateKey = '';
                }
            } catch (error) {
                console.error('加载配置失败:', error);
            }
        }

        // 打开模板内容编辑弹窗
        function editTemplateContent(templateKey) {
            window.currentTemplateKey = templateKey;
            const textarea = document.getElementById('templateContentTextarea');
            const modal = document.getElementById('templateContentModal');
            const title = document.getElementById('templateContentModalTitle');

            // 先清空并显示加载状态
            textarea.value = '加载中...';
            title.textContent = `编辑 ${templateKey} 参数`;
            modal.classList.add('show');

            // 从页面已有的配置中获取已有内容（如果已保存在后端）
            fetch(`${API_BASE}/admin/config?adminKey=${currentKey}&group=wechat`)
                .then(res => res.json())
                .then(data => {
                    if (data.code === 0) {
                        const contentKey = templateKey + '_content';
                        const content = data.data[contentKey]?.value || '';
                        textarea.value = content;
                        console.log('加载模板内容:', contentKey, content ? '有内容' : '空白');
                    } else {
                        textarea.value = '';
                        alert('加载失败: ' + (data.message || '未知错误'));
                    }
                })
                .catch(err => {
                    console.error('获取模板内容失败', err);
                    textarea.value = '';
                    alert('网络错误，请稍后重试');
                });
        }

        function closeTemplateContentModal() {
            document.getElementById('templateContentModal').classList.remove('show');
        }

        async function saveTemplateContent() {
            const content = document.getElementById('templateContentTextarea').value;
            const key = window.currentTemplateKey + '_content';
            const payload = {
                adminKey: currentKey,
                configs: { [key]: content }
            };
            try {
                const response = await fetch(`${API_BASE}/admin/config/save`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                const data = await response.json();
                if (data.code === 0) {
                    alert('模板内容保存成功');
                    closeTemplateContentModal();
                } else {
                    alert(data.message || '保存失败');
                }
            } catch (e) {
                console.error('保存模板内容异常', e);
                alert('网络错误');
            }
        }

        // 保存配置
        async function saveConfig() {
            const configs = {
                wechat_app_id: document.getElementById('wechat_app_id').value,
                wechat_app_secret: document.getElementById('wechat_app_secret').value,
                wechat_template_loan_apply: document.getElementById('template_loan_apply').value,
                wechat_template_loan_approve: document.getElementById('template_loan_approve').value,
                wechat_template_loan_reminder: document.getElementById('template_loan_reminder').value,
                wechat_template_repair_submit: document.getElementById('template_repair_submit').value,
                wechat_template_repair_accept: document.getElementById('template_repair_accept').value,
                wechat_template_repair_complete: document.getElementById('template_repair_complete').value,
                wechat_template_admin_repair_notify: document.getElementById('template_admin_repair_notify').value
            };

            try {
                const response = await fetch(`${API_BASE}/admin/config/save`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ adminKey: currentKey, configs })
                });
                const data = await response.json();

                if (data.code === 0) {
                    alert('保存成功！配置将在5分钟内生效');
                } else {
                    alert(data.message || '保存失败');
                }
            } catch (error) {
                console.error('保存配置失败:', error);
                alert('网络错误');
            }
        }

        // ========== 二维码管理相关函数 ==========

        let currentQRCodeUrl = '';

        // 显示二维码弹窗
        function showQRCodeModal(assetId) {
            const asset = allAssets.find(a => a.id === assetId);
            if (!asset) {
                console.error('未找到资产:', assetId);
                return;
            }

            const modal = document.getElementById('qrCodeModal');
            const display = document.getElementById('qrCodeDisplay');
            const info = document.getElementById('qrCodeAssetInfo');
            const urlDisplay = document.getElementById('qrCodeUrlDisplay');

            display.innerHTML = '';
            currentQRCodeUrl = asset.qr_code;

            // 生成二维码
            new QRCode(display, {
                text: asset.qr_code,
                width: 200,
                height: 200,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });

            info.textContent = `${asset.name} (${asset.asset_code || '无编号'})`;
            urlDisplay.textContent = asset.qr_code;

            modal.classList.add('show');
        }

        // 生成并显示二维码
        async function generateAndShowQR(assetId) {
            try {
                const response = await fetch(`${API_BASE}/qrcode/generate`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        assetId: parseInt(assetId),
                        domain: 'https://你的域名', // 默认域名
                        adminKey: currentKey
                    })
                });

                const data = await response.json();

                if (data.success && data.data) {
                    // 重新加载列表以获取最新信息
                    await loadAssets();

                    // 直接使用ID显示弹窗（loadAssets已更新allAssets）
                    showQRCodeModal(assetId);

                    alert('✅ 二维码生成成功！');
                } else {
                    alert('生成失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('生成失败:', error);
                alert('生成失败: ' + error.message);
            }
        }

        // 打印二维码
        function printQRCode() {
            const printWindow = window.open('', '_blank');
            const qrImg = document.querySelector('#qrCodeDisplay img').src;
            const info = document.getElementById('qrCodeAssetInfo').textContent;

            printWindow.document.write(`
                <html>
                <head>
                    <title>打印二维码 - ${info}</title>
                    <style>
                        body { text-align: center; font-family: Arial, sans-serif; margin-top: 50px; }
                        img { width: 300px; height: 300px; }
                        h2 { margin-bottom: 10px; }
                        p { color: #666; font-size: 12px; }
                    </style>
                </head>
                <body>
                    <h2>${info}</h2>
                    <img src="${qrImg}" />
                    <p>扫码报修</p>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.focus();
            setTimeout(() => {
                printWindow.print();
                printWindow.close();
            }, 500);
        }

        // 下载二维码图片
        function downloadQRCodeImage() {
            const qrImg = document.querySelector('#qrCodeDisplay img').src;
            const info = document.getElementById('qrCodeAssetInfo').textContent;

            const link = document.createElement('a');
            link.href = qrImg;
            link.download = `QRCode_${info}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

    </script>

    <!-- 版权信息 -->
    <div
        style="text-align: center; padding: 30px 20px; color: rgba(255,255,255,0.8); font-size: 14px; margin-top: 40px;">
        <p style="margin: 0 0 8px 0;">© 2025 广西商业学校练龙 版权所有</p>
        <p style="margin: 0; font-size: 12px; opacity: 0.7;">All Rights Reserved</p>
    </div>
</body>

</html>